package main

import (
	"encoding/json"
	"fmt"
)

// 结构体字段的可见性与JSON序列化
// 如果一个Go语言包中定义的标识符是首字母大写的，那么就是对外可见的
// 想要改变，不要首字母大写，需要编写Tag
type student struct {
	ID   int
	Name string
}
type class struct {
	Title    string `json:"title"`
	Students []student
}

func newStudent(id int, name string) student {
	return student{
		ID:   id,
		Name: name,
	}
}

func main() {
	c1 := class{
		Title:    "火箭班",
		Students: make([]student, 0, 20),
	}
	// 往班级添加学生
	for i := 0; i < 10; i++ {
		// 造十个学生
		tmpStu := newStudent(i, fmt.Sprintf("stu%02d", i))
		c1.Students = append(c1.Students, tmpStu)
	}
	fmt.Printf("%#v\n", c1)
	// JSON序列化，把Go语言数据 => JSON格式字符串
	data, err := json.Marshal(c1)
	if err != nil {
		fmt.Println("json marshal failed, err:", err)
		return
	}
	fmt.Printf("%T\n", data)
	fmt.Printf("%s\n", data)
	// JSON反序列化：JSON格式的字符串 => Go语言中的数据
	jsonStr := `{Title:"火箭班", Students:[]main.student{main.student{ID:0, Name:"stu00"}, main.student{ID:1, Name:"stu01"}, main.student{ID:2, Name:"stu02"}, main.student{ID:3, Name:"stu03"}, main.student{ID:4, Name:"stu04"}, main.student{ID:5, Name:"stu05"}, main.student{ID:6, Name:"stu06"}, main.student{ID:7, Name:"stu07"}, main.student{ID:8, Name:"stu08"}, main.student{ID:9, Name:"stu09"}}}`
	var c2 class
	err = json.Unmarshal([]byte(jsonStr), &c2)
	if err != nil {
		fmt.Println("JSON UnMarshaled Failed", err)
		return
	}
	fmt.Printf("%#v\n", c2)
}
